package it.yuzuojian.com.handle.mvc;

import it.yuzuojian.com.pojo.BeanFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StaticResourceHandle {
    private List<String> mvcStaticResources  = BeanFactory.getMvcStaticResources();
    public void handle(HttpServletRequest request, HttpServletResponse response,String servletPath) throws IOException {
        for (String mvcStaticResource : mvcStaticResources) {
            Pattern pattern = Pattern.compile(mvcStaticResource);
            Matcher matcher = pattern.matcher(servletPath);
            if (matcher.matches()) {
                String realPath = request.getSession().getServletContext().getRealPath(servletPath);
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"utf-8"));
                String type = servletPath.substring(servletPath.lastIndexOf("."));
                if(type.equals(".jpg")||type.equals(".png")){
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("image/jpeg");
                    FileInputStream fis = new FileInputStream(realPath);
                    ServletOutputStream outputStream = response.getOutputStream();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, len);
                    }
                    fis.close();
                    outputStream.close();
                }else {
                    PrintWriter out = response.getWriter();
                    response.setContentType("text/javascript;charset=UTF-8");
                    String line = null;
                    while((line = in.readLine()) != null){
                        out.println(line);
                        out.flush();
                    }
                    in.close();
                    out.close();
                }
            }
        }
    }

}
